package struts.servlet;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.bean.StrutsConfig;


public class ActionServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static final String ERROR="/error.jsp";

	public ActionServlet() {
		super();
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String path = req.getServletPath();
		String actionname = path.substring(0,path.indexOf("."));
		ServletContext context = req.getSession().getServletContext();
		Map<String, StrutsConfig> actionMap = (Map<String, StrutsConfig>)context.getAttribute("actionMap");
		StrutsConfig strutsConfig = actionMap.get(actionname);
		String method = strutsConfig.getMethod();
		String classname = strutsConfig.getActionClass();
		String url = "";
		try {
			Class<?> clazz = Class.forName(classname);
			Object instance = clazz.newInstance();
			Field[] fields=clazz.getDeclaredFields();
			for (Field field : fields) {
				String name = field.getName();
				String value = req.getParameter(name);
				String Name = name.substring(0, 1).toUpperCase() + name.substring(1);
				Method setterMethod = clazz.getDeclaredMethod("set"+Name, field.getType());
				setterMethod.invoke(instance, value);
			}
			Method excuteMethod = clazz.getDeclaredMethod(method, (Class[])null);
			String returnPara = (String)excuteMethod.invoke(instance, (Object[])null);
			url = strutsConfig.getResultMap().get(returnPara);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher = req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
	}
}
